package com.czk.queue.priorityQueue;

import java.util.*;

/**
 * 给你一个整数数组和整数k，返回出现频率前k元素
 * egg:
 * nums=[1,1,1,1,2,2,3] k=2
 * result=[1,2]
 *
 * @Author:ChenZhangKun
 * @Date: 2022/9/7 17:37
 */
public class TopKFrequent {

    public static void main(String[] args) {
        int[] arr = {1, 1, 1, 2, 2, 3};
        int[] ints = topKFrequent(arr, 2);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] topKFrequent(int[] arr, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : arr) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        // 创建优先队列
        PriorityQueue<Map.Entry<Integer, Integer>> priorityQueue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
        priorityQueue.addAll(map.entrySet());
        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = Objects.requireNonNull(priorityQueue.poll()).getKey();
        }
        return result;
    }
}
